<?php
namespace app\pay\controller\yop;

use think\Controller;
use pay\yop\Config;

use pay\yop\lib\Util\YopSignUtils;
use phpmailer\Email;
use customtool\Utils;

class Callback extends Controller {
    //结果通知返回原文数据
    public function index() {    
//        $source = $_REQUEST["response"]; 
        $data = input('post.'); 
        //返回的密文
        $source = $data['source'];
       
        $resPayPlatform = model('PayPlatform')->get(['id' => $data['id']]);
        //还原出原文
        $decryptData = YopSignUtils::decrypt($source, $resPayPlatform->private_key, $resPayPlatform->public_key);
        
        $dataArr = json_decode($decryptData, true);
        
        // 检测商户订单号
        $resPayBisOrder = model('PayBisOrder')->get(['mchnt_orderid' => $dataArr['orderId']]);
        if($resPayBisOrder) {
            $payAmount = $resPayBisOrder->pay_amount; // 订单金额
            // 检测交易金额
            if($dataArr['status'] == 'SUCCESS' && $dataArr['orderAmount'] * 100 == (string)$payAmount) {
                // 发送邮件
                Email::send('wowchky@163.com', '易宝支付成功订单' . $dataArr['orderId'], $decryptData);

                $resPayBis = model('PayBis')->get(['merchant_id' => $resPayBisOrder->merchant_id]);
                // $resPayPlatform = model('PayPlatform')->get(['id' => $resPayBis->platform_id]);
                /*
                 *  更新订单信息
                 */
                // 手续费分析处理
                $resFeeHandle = $this->feeHandle($payAmount, $dataArr, $resPayBis, $resPayPlatform);
                
                Utils::log('pay/yop/callback/index', $dataArr['orderId'], '易宝异步回调实际到帐' . $resFeeHandle['actual_amount']);
                
                payBisOrderUpdate($resPayBisOrder->id, $resFeeHandle['pay_fee'], $resFeeHandle['mchnt_fee'], $resFeeHandle['actual_amount']); 
                
                /*
                 * 更新商户可用余额 
                 */            
                $amount = $resPayBis->amount;
                $platformAmount = $resPayBis->platform_amount;
                $payBisData = [
                    'mchnt_pre_fee'   => $resFeeHandle['mchnt_pre_fee'],
                    'amount'          => $resFeeHandle['actual_amount'] + $amount,
                    'platform_amount' => $resFeeHandle['actual_amount'] + $resFeeHandle['mchnt_fee'] + $platformAmount,
                ];
                // 更新商户可用余额 
                model('PayBis')->updateById($payBisData, $resPayBis->id);
                
                /*
                 * 通过消息队列的形式给请求方推送异步通知 
                 *
                 * 推送异步通知给客户端提供的回调地址
                 */           
                // 异步返回给客户端的数据组装
                $result = $this->responseData($resPayBisOrder->merchant_id, $decryptData, $resPayBis->md5key);
                
                // 消息队列
                \think\Queue::push('app\queue\controller\Index@fire', $result, $queue = 'payCallbackQueue');
                return true;
            }  
        }
    }
    
    /*
     *  手续费分析处理
     */
    private function feeHandle($payAmount, $dataArr, $resPayBis, $resPayPlatform) {
        if($dataArr['platformType'] == 'NCPAY') { // 快捷支付
            // 畅远手续费
            $mchntFee = round($payAmount * $resPayBis->mchnt_yjzf_rate / 100);
            // 易宝手续费
            $payFee   = round($payAmount * $resPayPlatform->yjzf_rate / 100);
        }
        if($dataArr['platformType'] == 'NET') { // 网银支付
            // 畅远手续费
            $mchntFee = round($payAmount * $resPayBis->mchnt_netb2c_rate / 100);
            // 易宝手续费
            $payFee   = round($payAmount * $resPayPlatform->netb2c_rate / 100);
        }

        if($resPayBis->is_prepay == 1) { // 预充手续费
            $actualAmount = $dataArr['payAmount'] * 100 - $payFee; // 给客户的实际到帐为易宝实付金额
            // 变更商户可用的预充手续费
            $mchntPreFee = $resPayBis->mchnt_pre_fee - $mchntFee;
        } else {
            $actualAmount = $dataArr['payAmount'] * 100 - $mchntFee - $payFee; // 给客户的实际到帐，易宝实付金额－畅远手续费-平台手续费
            // 商户可用的预充手续费不变
            $mchntPreFee = $resPayBis->mchnt_pre_fee;
        }
        $resArr = array(
            'pay_fee'        => $payFee,
            'mchnt_fee'      => $mchntFee,
            'mchnt_pre_fee'  => $mchntPreFee,
            'actual_amount'  => $actualAmount
            
        );
        return $resArr;
    }
    
    /*
     *  异步返回给客户端的数据组装
     */
    private function responseData($merchantId, $data, $md5key) {
        $retData = json_decode($data, true);
        if($retData['status'] == 'SUCCESS') {
            $result = array(
                'bank_trxid'    => $retData['bankTrxId'],  // 流水号
                'mchnt_orderid' => $retData['orderId'], // 商户订单号
                'pay_orderid'   => $retData['uniqueOrderNo'], // 系统订单号
                'merchant_id'   => $merchantId, // 商户号
                'pay_amount'    => $retData['payAmount'], // 订单金额，此时金额单位为元，后续转换为分
                'actual_amount' => $retData['orderAmount'], // 实际到帐金额，此时金额单位为元，后续转换为分
                'payment_time'  => $retData['bankPaySuccessDate'], // 完成时间
                'platform_type' => $retData['platformType'] // 支付类型
            );
            return callbackTrue($result, $md5key);
        } else {
            return retMsgFalse($retData['status']);
        }
    }
}